﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ITAP.ContourBuilder.Components;

using ITAP.ContourBuilder.Components.Dimensions;
using System.Drawing;
using ITAP.Core.Modelling;

namespace ITAP.ContourBuilder.Manipulation
{
    public class CommandAddElementDimension : SerializedCommand
    {
        public CommandAddElementDimension(ContourControl control)
            : base(control)
        {

        }

        ContourElementDimension dimension = null;
        PointF prevMousePoint;
        public override void ObtainPeripheryState(GlobalPeripheryState state)
        {
            base.ObtainPeripheryState(state);
            // Выбираем элемент для создания размера
            if (state.MouseState.MouseMode == MouseMode.Down && state.MouseState.State.Button == MouseButtons.Left)
            {
                //if (dimension == null)
                //{
                    IEnumerable<IContourComponent> allComponents = this.control.ContourContainer.GetAllInnerComponents();
                    ModelPoint point = this.ScreenPointToModelPoint(state.MouseState.State.Location);
                    ContourElement element = null;
                    foreach (IContourComponent component in allComponents)
                        if (component is ContourElement && component.CanSelectByPoint(point))
                            element = component as ContourElement;

                    if (element == null)
                    {
                        this.Cancel();
                        return;
                    }

                    dimension = (ContourElementDimension)DimensionFactory.CreateContourElementDimension(element, GlobalData.DimensionTextFont, "L");
                    element.GetRootModel().AddInnerComponent(dimension);
                    this.control.ContourContainer.Update();
                    prevMousePoint = state.MouseState.State.Location;
            }
            else if (state.MouseState.MouseMode == MouseMode.Move && state.MouseState.State.Button == MouseButtons.Left
                & dimension != null)
            {
                ModelPoint prevPoint = this.ScreenPointToModelPoint(prevMousePoint);
                ModelPoint point = this.ScreenPointToModelPoint(state.MouseState.State.Location);
                ModelVector vector = new ModelVector(prevPoint, point);
                dimension.OffsetFromPrimitive += vector.Y;

                prevMousePoint = state.MouseState.State.Location;
                dimension.Recalculate();
                this.control.Invalidate();
            }
            else if(state.MouseState.MouseMode == MouseMode.Up && state.MouseState.State.Button == MouseButtons.Left)
            {
                this.control.UpdateModel();
                this.Exit();
            }
        }

        public override string ToString()
        {
            return "Создать размер элемента";
        }
    }
}
